package ue.networking;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import ue.core.Galaxy;

public class Server {
	
	protected int port;
	protected ServerSocket server;
	
	protected ArrayList<Client> clients;
	
	protected ClientListener clientListener;
	protected Thread clientListenerThread;
	
	protected int idCount;
	
	protected AccountSystem accountSystem;
	
	public Server(int port) {
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
		}
		this.port = port;
	
		idCount = 0;
		
		clients = new ArrayList<Client>();
		
		accountSystem = new AccountSystem("res/accounts/accountSystem.xml");
		
		clientListener = new ClientListener();
		clientListenerThread = new Thread(clientListener);
		clientListenerThread.start();
	}
	
	public void run() {
		for(int i = clients.size() - 1; i >= 0; i--) {
//			System.out.println(clients.get(i).getStatus());
			if(clients.get(i).getStatus() != Client.Status.DISCONNECTED) {
				clients.get(i).run();
			} else {
				System.out.println(Galaxy.getTimestamp() + "Removed Client " + clients.get(i).getID());
				clients.remove(i);
			}
		}
	}
	
	protected class ClientListener implements Runnable {
		
		@Override
		public void run() {
			for(;;) {
				try {
					Socket socket = server.accept();
					
					if(socket == null)
						continue;
					
					System.out.println("Client " + idCount + " connected");
					clients.add(new Client(socket, idCount++));
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
}
